//
//  CommonRouteVC.m
//  NtoccShipper
//
//  Created by mac on 2019/11/28.
//  Copyright © 2019 zhuchongjin. All rights reserved.
//

#import "CommonRouteVC.h"
#import "CommonRouteCell.h"
#import "AddNewCommonRouteVC.h"
#import "CommonRouteModel.h"
#import "CommonRouteCellNew.h"


@interface CommonRouteVC ()<UITableViewDelegate,UITableViewDataSource>
{
    FlexFrameView *header;
}
@property (nonatomic,strong) CommonRouteCell *commonRouteCell;
@property (nonatomic,strong) CommonRouteCellNew *commonRouteCellNew;
@property (nonatomic,strong) CJTableView *tableView;
@property (nonatomic,strong) NSMutableArray *modelArray;
@property (nonatomic,strong) NSString *refreshType; //刷新
@property (nonatomic,readwrite) int page;
@property (nonatomic,copy) NSString *strSearchInfo; // 搜索内容
@property (nonatomic,strong) CJTextField *fieldSerach;

@end

@implementation CommonRouteVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setTitleName:CJLString(@"常用路线")];
    [self setBackLeftButton:@""];
    [self setRightImage:CJLString(@"新增路线") image:@""];
    self.strSearchInfo = @"";

    self.commonRouteCell = [[CommonRouteCell alloc]initWithFlex:nil reuseIdentifier:nil];
    self.commonRouteCellNew = [[CommonRouteCellNew alloc]initWithFlex:nil reuseIdentifier:nil];
    [self createTopView];
    [self.view addSubview:self.tableView];
    WS(ws);
    self.tableView.placeHolderView = [[KKTableViewNoDataView alloc] initWithFrame:self.tableView.bounds image:[UIImage imageNamed:@"no_data"] viewClick:^{
           [ws.tableView.mj_header beginRefreshing];
    }];
    [self initData];
    [self loadData];
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    self.massageButton.titleLabel.font = [UIFont cjTitleFont14];
    [self.massageButton setTitleColor:[UIColor cjSubheadTextColor] forState:UIControlStateNormal];
    [self.tableView.mj_header beginRefreshing];

}
- (void)RightTextClick:(UIButton *)sender{
    AddNewCommonRouteVC *vc = [AddNewCommonRouteVC new];
    vc.isEditorRoute = @"0";
    vc.strTitle = @"新增常用路线";
    [self pushVc:vc];
}

- (void)createTopView{
    //    WS(ws);
    CGRect rcFrame = CGRectMake(0, kTopHeight, [[UIScreen mainScreen] bounds].size.width, 0);
    header = [[FlexFrameView alloc] initWithFlex:@"CommonRouteVCTopView" Frame:rcFrame Owner:self];
    header.flexibleHeight = YES;

    [header layoutIfNeeded];
    [self.view addSubview:header];
}


- (void)btnSerachRouteView{
    
    if ([CJRegular getIsStrEmpty:self.fieldSerach.text]) {
        [CJAlert showStringDismissWithDelay:@"请填写搜索内容"];
    }else{
        [self.tableView.mj_header beginRefreshing];

//        [self downRefresh];
    }
}

- (void)initData{
    self.modelArray = [[NSMutableArray alloc]init];
    self.page = 1;
}

/// <#Description#>
- (void)loadData {

    NSString *strURL = CJStringWithFormat(@"%@/ntocc-basic-api/commonRouteInfo",CJBaseUrl);
    NSDictionary *dicPar = @{@"pageNum":CJStringWithFormat(@"%d",self.page),
                             @"pageSize":@"10",
                             @"searchInfo":self.fieldSerach.text
                            };

    WS(ws);
    DLog(@"==== %@",dicPar);
    
    [[HDNetworking sharedHDNetworking] GET:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {

        DLog(@"++++++++%@",responseObject);
        NSArray *list = responseObject[@"records"];
        NSString *total = CJStringWithFormat(@"%@",responseObject[@"total"]);
//        if (list.count > 0) {

            if ([ws.refreshType isEqualToString:@"down"]) {
                 [ws.modelArray removeAllObjects];
             }
            
            NSError * error ;
            NSArray *arr = [CommonRouteModel arrayOfModelsFromDictionaries:list error:&error];
            [ws.modelArray addObjectsFromArray:arr];
            [ws.tableView.mj_header endRefreshing];
            [ws.tableView.mj_footer endRefreshing];

            if (ws.modelArray.count == total.intValue) {
              [ws.tableView.mj_footer endRefreshingWithNoMoreData];
            }

//        }else{
//            
//            [ws.tableView.mj_header endRefreshing];
//            [ws.tableView.mj_footer endRefreshingWithNoMoreData];
//        }
        [ws.tableView reloadData];
    } failure:^(NSError * _Nonnull error) {
        DLog(@"++++++++%@",error);
        [ws.tableView.mj_header endRefreshing];
        [ws.tableView.mj_footer endRefreshing];
    }];

}


- (void)downRefresh
{
    self.refreshType = @"down";
    self.page = 1;
    [self loadData];
}

- (void)upRefresh
{
    self.refreshType = @"up";
    self.page ++;
    [self loadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArray.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([CJControl getUIWithNew]) {

        static NSString *identifier = @"CommonRouteCellNew";
        CommonRouteCellNew *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[CommonRouteCellNew alloc] initWithFlex:nil reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;

        }
        CommonRouteModel *model  = self.modelArray[indexPath.row];
        [cell setCellInfoWithModel:model];

        WS(ws);
        cell.blockDelecte = ^(id anyObject) {
            [ws btnDelecteAction:indexPath.row];
        };
        cell.blockChange = ^(id anyObject) {
            [ws btncHangeAction:indexPath.row];
        };

        return cell;
    }else{
        static NSString *identifier = @"CommonRouteCell";
        CommonRouteCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[CommonRouteCell alloc] initWithFlex:nil reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;

        }
        CommonRouteModel *model  = self.modelArray[indexPath.row];
        [cell setCellInfoWithModel:model];

        WS(ws);
        cell.blockDelecte = ^(id anyObject) {
            [ws btnDelecteAction:indexPath.row];
        };
        cell.blockChange = ^(id anyObject) {
            [ws btncHangeAction:indexPath.row];
        };

        return cell;
    }

    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (self.clickBack) {
        CommonRouteModel *model = self.modelArray[indexPath.row];
        if (self.blockCommonRoute) {
            self.blockCommonRoute(model);
        }
        [self pop];
    }
    
}


- (void)btnDelecteAction:(NSInteger )index{
    WS(ws);
    CJAlertView *alert = [[CJAlertView alloc]initWithTitle:@"" strContent:@"您确定要删除该条路线吗？" ClickOnSure:^(NSString * _Nonnull strSure) {
        [ws btnDelecteIsSureAction:index];
    } ClickOnCancle:^(NSString * _Nonnull strCancle) {
        
    }];
    alert.center = KEYWINDOW.center;
    WLAlertView * alertView = [[WLAlertView alloc]init];
    alertView.containerView = alert;
    alertView.isTouchOtherUndissmiss = YES;
    [alertView show];


}

- (void)btnDelecteIsSureAction:(NSInteger )index{
    CommonRouteModel *model = self.modelArray[index];
    
    NSString *strURL = CJStringWithFormat(@"%@/ntocc-basic-api/commonRouteInfo",CJBaseUrl);
    NSDictionary *dicPar = @{@"codes":model.code
                            };
    
    WS(ws);
    
    
    [[HDNetworking sharedHDNetworking] DELETE:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
        
//        DLog(@"++++++++%@",responseObject);
        [ws.tableView.mj_header beginRefreshing];
   
        
    } failure:^(NSError * _Nonnull error) {
        DLog(@"++++++++%@",error);
        
    }];
}

- (void)btncHangeAction:(NSInteger )index{
    CommonRouteModel *model = self.modelArray[index];

    AddNewCommonRouteVC *vc = [[AddNewCommonRouteVC alloc]init];
    vc.isEditorRoute = @"1";
    vc.strTitle = @"修改常用路线";
    vc.commonRouteModel = model;
    [self pushVc:vc];
}



- (CJTableView *)tableView{
    if (!_tableView) {
        _tableView = CJTableView.tbInitFrameStyle(CGRectMake(0, kTopHeight + header.height + CJTableToTopHeight, SCREEN_WIDTH, SCREEN_HEIGHT-kTopHeight  - header.height -CJTableToTopHeight),UITableViewStylePlain)
        .tbDelegate(self)
        .tbDataSource(self)
        .tbSetOther(YES)
        .tbEstimatedRowHeight(YES)
        .tbMjHeadFooter(YES)
        ;
        WS(ws);
        _tableView.blockMjHeader = ^(BOOL isheader) {
            
            if (isheader) {
                [ws downRefresh];
            } else {
                [ws upRefresh];
            }
        };
    }
    return _tableView;
}


@end
